//
//  TZOauthController.swift
//  WeiboWithSwift
//
//  Created by 涂真 on 15/12/19.
//  Copyright © 2015年 涂真. All rights reserved.
//

import UIKit
import SVProgressHUD
class TZOauthController: UIViewController,UIWebViewDelegate {
    
    ///webView开始加载的时候
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Gradient)
    }
    
    ///webView加载完毕
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    ///webView是否要去加载一个网址，返回ture加载，返回false不去加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!.absoluteString
        //TODU:打印头像url
//        print("rul:\(url)")
        if !url.hasPrefix(TZNetWorkTool.shardNetWorkTool.redirect_uri){
            return true
        }
        //是回调地址，判断是是授权还是取消
        // 点击取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        // 点击授权:会以code=开头 http://www.baidu.com/?code=a61c2d7ec7b8c4c9c1962bf4354354c5
        //获取url中？号后面的东西，URL?.query就是问好后面的东西
        if let query = request.URL?.query{
            let codeStr = "code="
            //如果是query是code=开头的话
            if query.hasPrefix(codeStr){
                //截取code的值
                let code = (query as NSString).substringFromIndex(codeStr.characters.count)
                //TODU:打印code
//                print("code:\(code)")
                loadAccessToken(code)
                
            }else{
                
                self.close()
            }
            
        }else{
            print("query没有值")
        }
        
        return false
    }
    
    //MARK: - 控制器加载AccessToken
    ///控制器加载AccessToken
    func loadAccessToken(code:String){
        TZNetWorkTool.shardNetWorkTool.loadAccessToken(code) { (result, error) -> () in
            //无法获取access_token
            if error != nil{
                print("error:\(error)")
                SVProgressHUD.showInfoWithStatus("您的网路不给力")
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return
            }
            //结果没有错，可以获取access_token
            let account = TZUserAccount(dict: result!)
            //保存对象到沙河
            account.saveAccountInfo()
            //切换到欢迎界面
            (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(false)
            //关闭登录界面
            self.close()
//            print("account\(account)")
        }
    }
    
    //MRK: - 通过这个方法替换自身的view，生成WebView
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let request = NSURLRequest(URL:TZNetWorkTool.shardNetWorkTool.oauthUrl())
        webView.loadRequest(request)
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.title = "登陆"
    }
    
    //MARK: - 导航栏点击事件
    func autoFill(){
        
        //创建js代码
        let js = "document.getElementById('userId').value='13926437204',document.getElementById('passwd').value='DasKing8701226'"
        //webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    func close(){
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 懒加载
    lazy var webView = UIWebView()
}
